package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonParser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class WxSignatureUtil {

    @Autowired
    private RedisCache redisCache;
    /**
     * 开发者ID，必填
     * 微信公众号开发者平台上的凭据 AppId
     */
    private static final String APPID = "wx032eaa086bf37cec";
    /**
     * 开发者秘钥，必填
     * 微信公众号开发者平台上的凭据 AppSecret
     */
    private static final String SECRET = "c5470d478eb775f419f39dd155f77d56";
    /**
     * 授权码发放类型
     */
    private static final String GRANT_TYPE = "client_credential";
    /**
     * 授权码类型
     */
    private static final String TYPE = "jsapi";
    /**
     * 获取微信 TOKEN 接口
     */
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    /**
     * 获取微信令牌接口
     */
    private static final String TICKET_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    /**
     * 请求参数名
     */
    private static final String ACCESS_TOKEN_KEY = "access_token";
    /**
     * TICKET_KEY
     */
    private static final String TICKET_KEY = "ticket";

    /**
     * JSON 解析
     */

    /**
     * 获取签名
     * 注意 URL 一定要动态获取，不能 hardcode
     *
     * @param url
     * @return
     */
    public Map<String, String> getWechatSignature(String url) {
        System.out.println("=============================url");
        System.out.println(url);
        // 获取token
        String token = getToken();
        // 获取ticket
        String ticket = getTicket(token);
        // 随机字符串
        String nonceStr = UUID.randomUUID().toString();
        System.out.println("=============================nonceStr");
        System.out.println(nonceStr);
        // 时间戳
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        System.out.println("=============================timestamp");
        System.out.println(timestamp);
        //注意这里参数名必须全部小写，且必须有序
        String context = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
        //加密
        String signature = SHA1(context);
        //封装
        Map<String, String> result = new HashMap<String, String>();
        result.put("jsapi_ticket", ticket);
        result.put("nonceStr", nonceStr);
        result.put("timestamp", timestamp);
        result.put("signature", signature);
        System.out.println("=============================signature");
        System.out.println(signature);

        return result;
    }

    /**
     * 获取 token
     *
     * @return
     */
    public String getToken() {
        String cache = redisCache.getCacheObject("access_token");
        if (!StringUtils.isEmpty(cache)) {
            System.out.println("==============================access_token");
            System.out.println("access_token");
            System.out.println(cache);
            return cache;
        }
        // https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=&secret=xxxxxxxxx
        String url = ACCESS_TOKEN_URL + "?grant_type=" + GRANT_TYPE + "&appid=" + APPID + "&secret=" + SECRET;
        //请求链接获取token
        JSONObject jsonObject = httpGetForJson(url);
        String access_token = jsonObject.getString("access_token");
        redisCache.setCacheObject("access_token", access_token, 7000, TimeUnit.SECONDS);
        return  access_token;
    }

    /**
     * 获取 ticket
     *
     * @param token
     * @return
     */
    public String getTicket(String token) {
        String cache = redisCache.getCacheObject("ticket");
        if (!StringUtils.isEmpty(cache)) {
            System.out.println("==============================ticket");
            System.out.println("ticket");
            System.out.println(cache);
            return cache;
        }
        // https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=xxxx&type=jsapi
        String url = TICKET_URL + "?access_token=" + token + "&type=" + TYPE;
        //请求链接获取token
        JSONObject response = httpGetForJson(url);
        String ticket = response.getString("ticket");
        redisCache.setCacheObject("ticket", ticket, 7000, TimeUnit.SECONDS);
        return ticket;
    }

    /**
     * SHA1加密
     *
     * @param value
     * @return
     */
    public String SHA1(final String value) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-1");
            digest.update(value.getBytes());
            byte messageDigest[] = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 发送请求
     *
     * @param url
     * @return
     */
    public JSONObject httpGetForJson(String url) {
        RestTemplate restTemplate = new RestTemplate();
        String result = restTemplate.getForObject(url, String.class);
        return JSONObject.parseObject(result);
    }

}